﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agile.Engine.Data;
using Agile.Engine.Utils;
using System.Data;

namespace Fis.Web.Rules.Book
{
    public class GLobleRule : DynamicRule
    {

        string Master = "TBILLMASTER";
        string Detail = "TBILLDETAIL";

        public int BillSequnce(string range)
        {
            var da = new DataAccess() { Context = Model.DataContext, TableName = Master };
            return da.Scalar(0, "MAX(FNO)", string.Format("DATEPART(month, FENTERDATE) = {0}", range)) + 1;
        }

        void AddNew(System.Data.DataRow mst, System.Data.DataRow[] dtl)
        {

            mst["FNO"] = BillSequnce(BookRange);
            mst["FSYNC"] = 1;

            //mst["SID"] = Guid.NewGuid().ToString();
            mst["SINDEXDATE"] = DateTime.Now;
            mst["SBOOKID"] = BookID;
            mst.AcceptChanges();
            mst.SetAdded();

            foreach (var d in dtl)
            {

                var valid = Model.Count("TACCOUNT", "SID", string.Format("FPARENT='{0}'", d["FACCOUNTCODE"]));

                if (valid > 0)
                {
                    Message = string.Format("科目{0}不是最子级科目", d["FACCOUNTCODE"]);
                    throw new Exception(Message);
                }

                d["FVCHID"] = mst["SID"];
                d["SID"] = Guid.NewGuid().ToString();
                d["SINDEXDATE"] = DateTime.Now;
                d["SBOOKID"] = BookID;

                d.AcceptChanges();
                d.SetAdded();
            }


            Model.UpdateTable(Master, "SID", mst);
            Model.UpdateTable(dtl.CopyToDataTable(), Detail, string.Format("FVCHID='{0}'", mst["SID"]));
        }

        void Modify(System.Data.DataRow mst, System.Data.DataRow[] dtl)
        {
            mst["FSYNC"] = 1;
            mst["SBOOKID"] = BookID;
            mst.AcceptChanges();
            mst.SetModified();

            foreach (var d in dtl.AsEnumerable())
            {

                var valid = Model.Count(Detail, "TACCOUNT", string.Format("FPARENT='{0}'", d["FACCOUNTCODE"]));

                if (valid > 0)
                {
                    Message = string.Format("科目{0}不是最子级科目", d["FACCOUNTCODE"]);
                    throw new Exception(Message);
                }

                d["SINDEXDATE"] = DateTime.Now;

                d.AcceptChanges();
                d.SetModified();
            }

            Model.UpdateTable(Master, "SID", mst);
            Model.UpdateTable(dtl.CopyToDataTable(), Detail, string.Format("FVCHID='{0}'", mst["SID"]));
        }

        void Delete(string sid)
        {
            var fno = Model.ExecuteScalar(0, "SELECT FNO FROM TBILLMASTER WHERE SID='" + sid + "'");
            Model.Delete(Master, "SID='" + sid + "'");
            Model.Delete(Detail, "SID='" + sid + "'");

            //删除后凭证号前移
            Model.ExecuteNonQuery(string.Format(
                @"UPDATE {0} SET FNO=FNO-1, SINDEXDATE=GETDATE() WHERE FNO>={1} AND DATEPART(month, FENTERDATE) = {2}"
                , Master
                , fno
                , BookRange));

            CommonRule common = new CommonRule();
            common.UpdateDeleteInfo(Model.DataContext, Master, sid, BookID);
            common.UpdateDeleteInfo(Model.DataContext, Detail, sid, BookID);

        }

        void Sync(System.Data.DataTable mst, System.Data.DataTable dtl)
        {
            foreach (var d in mst.AsEnumerable())
            {
                AddNew(d, dtl.Select(string.Format("FVCHID='{0}'", d["SID"])));
            }
        }

        void SyncByRange(ref System.Data.DataTable mst, ref System.Data.DataTable dtl)
        {
            Master = "TBILLMASTER";
            Detail = "TBILLDETAIL";

            var range = int.Parse(Paramater["RANGE"].ToString());
            //按期间同步
            if (range > 0)
            {
                mst = Model.QueryTable(Master, string.Format("DATEPART(month, FENTERDATE) = {0}", Paramater["RANGE"]));
                dtl = Model.QueryTable(Detail, string.Format(
                    "FVCHID in (SELECT SID FROM {0} WHERE DATEPART(month, FENTERDATE) = {1})", Master, Paramater["RANGE"]));
            }
            else //初始化同步
            {
                var startime = Model.QueryTable("TBOOK").Rows[0]["FBOOKSTARTIME"].ToString();
                mst = Model.QueryTable(Master, "FENTERDATE<'" + startime + "'");
                dtl = Model.QueryTable(Detail, string.Format(
                    "FVCHID in (SELECT SID FROM {0} WHERE {1})", Master, "FENTERDATE<'" + startime + "'"));

            }


        }

        public override void ExecuteNonTrans()
        {
            var action = Paramater["Action"].ToString();
            System.Data.DataTable mst = null, dtl = null;
            Status = 1;

            switch (action)
            {
                case "AddNew":
                    mst = ZipUtils.UnZipDataTable(Paramater["master"].ToString());
                    dtl = ZipUtils.UnZipDataTable(Paramater["detail"].ToString());
                    AddNew(mst.Rows[0], dtl.Select());
                    break;
                case "Modify":
                    mst = ZipUtils.UnZipDataTable(Paramater["master"].ToString());
                    dtl = ZipUtils.UnZipDataTable(Paramater["detail"].ToString());
                    Modify(mst.Rows[0], dtl.Select());
                    break;
                case "Delete":
                    Delete(Paramater["SID"].ToString());
                    break;
                case "Range":
                    SyncByRange(ref mst, ref dtl);
                    break;

            }

            if (mst != null && mst.Rows.Count > 0)
            {
                Result["master"] = ZipUtils.ZipDataTable(mst);
                Result["detail"] = ZipUtils.ZipDataTable(dtl);
            }

        }
    }
}
